<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片区域 -->
    <el-card>
      <!-- 头部警告框 -->
      <el-alert
        title="注意:只允许第三级分类设置相关参数!"
        type="warning"
        show-icon
        :closable="false"
      >
      </el-alert>
      <!-- 搜索框 -->
      <el-row>
        <el-col>
          <span>选择分类:</span>
          <el-cascader
            v-model="selectedKeys"
            clearable
            :options="catelist"
            :props="{
              expandTrigger: 'hover',
              value: 'cat_id',
              label: 'cat_name',
              checkStrictly: true,
            }"
            @change="handleCascaderChange"
          ></el-cascader>
        </el-col>
      </el-row>

      <!-- tabs 页签区域 -->
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <!-- 动态参数列表 -->
        <el-tab-pane label="动态参数" name="many">
          <el-button
            type="primary"
            size="mini"
            :disabled="isBtnDisable"
            @click="showAddDialog"
            >添加参数</el-button
          >
          <!-- 列表区域 -->
          <el-table :data="manyTableData" stripe border style="width: 100%">
            <el-table-column label="" type="expand">
              <template slot-scope="scope">
                <el-tag
                  size="small"
                  v-for="(item, index) in scope.row.attr_vals"
                  :key="index"
                  closable
                  @close="handleRemoveAttr(index,scope.row)"
                  >{{ item }}</el-tag
                >
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column label="#" type="index"></el-table-column>
            <el-table-column
              prop="attr_name"
              label="参数名称"
            ></el-table-column>
            <el-table-column label="操作" width="300px">
              <template slot-scope="scope">
                <!-- 修改按钮 -->
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="showEditDialog(scope.row)"
                  >编辑</el-button
                >
                <!-- 删除按钮 -->
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="deleteAttr(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <!-- 静态参数列表 -->
        <el-tab-pane label="静态属性" name="only">
          <el-button
            type="primary"
            size="mini"
            :disabled="isBtnDisable"
            @click="showAddDialog"
            >添加属性</el-button
          >

          <!-- 列表区域 -->
          <el-table :data="onlyTableData" stripe border>
            <el-table-column label="" type="expand">
              <template slot-scope="scope">
                <el-tag
                  size="small"
                  v-for="(item, index) in scope.row.attr_vals"
                  :key="index"
                  closable
                   @close="handleRemoveAttr(index,scope.row)"
                  >{{ item }}</el-tag
                >
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column label="#" type="index"></el-table-column>
            <el-table-column
              prop="attr_name"
              label="属性名称"
            ></el-table-column>
            <el-table-column label="操作" width="300px">
              <template slot-scope="scope">
                <!-- 修改按钮 -->
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="showEditDialog(scope.row)"
                  >编辑</el-button
                >
                <!-- 删除按钮 -->
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="deleteAttr(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加对话框 -->
    <el-dialog
      :title="'添加' + titleText"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogClose"
    >
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addAttr">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改对话框 -->
    <el-dialog
      :title="'修改' + titleText"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClose"
    >
      <el-form
        :model="editForm"
        :rules="editFormRules"
        ref="editFormRef"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editAttr">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data () {
    return {
      // 存放所有商品列表数据
      catelist: [],
      //  存放的是分类的id
      selectedKeys: [],
      activeName: 'many',
      onlyTableData: [],
      manyTableData: [],
      addDialogVisible: false,
      addForm: {
        attr_name: ''
      },
      addFormRules: {
        attr_name: [
          { required: true, message: '请输入属性名称', trigger: 'blur' }
        ]
      },
      editDialogVisible: false,
      editForm: {
        attr_name: ''
      },
      editFormRules: {
        attr_name: [
          { required: true, message: '请输入属性名称', trigger: 'blur' }
        ]
      },
      attrId: undefined

    }
  },
  created () {
    this.getCateList()
  },
  methods: {
    // 获取所有商品分类列表
    async getCateList () {
      const { data: res } = await this.$http.get('categories')
      this.catelist = res.data
    },
    // 获取参数列表的数据
    async getParamsData () {
      const { data: res } = await this.$http.get(
        'categories/' + this.cateId + '/attributes',
        { params: { sel: this.activeName } }
      )
      // console.log(res)
      res.data.forEach((t) => {
        t.attr_vals = t.attr_vals ? t.attr_vals.split(' ') : []
        t.inputVisible = false
        t.inputValue = ''
      })

      if (this.activeName === 'many') {
        this.manyTableData = res.data
      } else {
        this.onlyTableData = res.data
      }
    },
    // 级联选择框改变数据的时候触发
    handleCascaderChange () {
      // 只允许第三级分类设置相关参数!
      if (this.selectedKeys.length !== 3) {
        this.selectedKeys = []
        this.manyTableData = []
        this.onlyTableData = []
        return
      }
      this.getParamsData()
    },
    // 点击动态参数和静态属性的时候触发
    handleTabClick () {
      this.getParamsData()
    },
    showAddDialog () {
      this.addDialogVisible = true
    },
    addDialogClose () {
      this.$refs.addFormRef.resetFields()
    },
    addAttr () {
      this.$refs.addFormRef.validate(async (valid) => {
        // console.log(valid)
        if (valid) {
          // 验证通过
          const { data: res } = await this.$http.post(
            'categories/' + this.cateId + '/attributes',
            { ...this.addForm, attr_sel: this.activeName }
          )
          if (res.meta.status !== 201) {
            return this.$message({
              message: '添加参数失败',
              type: 'error',
              showClose: true,
              duration: 3000
            })
          }
          this.$message({
            message: '添加参数成功',
            type: 'success',
            showClose: true,
            duration: 3000
          })
          this.addDialogVisible = false
          this.getParamsData()
        }
      })
    },
    editDialogClose () {
      this.$refs.editFormRef.resetFields()
    },
    showEditDialog (row) {
      // console.log(row)
      this.editDialogVisible = true
      this.attrId = row.attr_id
    },
    editAttr () {
      this.$refs.editFormRef.validate(async (valid) => {
        // console.log(valid)
        if (valid) {
          // 验证通过
          const { data: res } = await this.$http.put(
            'categories/' + this.cateId + '/attributes/' + this.attrId,
            { attr_sel: this.activeName, ...this.editForm }
          )
          if (res.meta.status !== 200) {
            return this.$message({
              message: '添加属性失败',
              type: 'error',
              showClose: true,
              duration: 3000
            })
          }
          this.$message({
            message: '添加属性成功',
            type: 'success',
            showClose: true,
            duration: 3000
          })
          this.editDialogVisible = false
          this.getParamsData()
        }
      })
    },
    // 点击删除按钮
    deleteAttr (id) {
      this.$confirm('是否删除', '提示', {
        confirmButtonText: '是',
        cancelButtonText: '否',
        type: 'warning'
      })
        .then(async (action) => {
          await this.$http.delete(
            'categories/' + this.cateId + '/attributes/' + id
          )
          this.getParamsData()
        })
        .catch(() => {
          this.$message({
            message: '取消删除',
            type: 'error',
            showClose: true,
            duration: 3000
          })
        })
    },
    showInput (row) {
      row.inputVisible = true
      // 让文本框自动获得焦点
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    async saveAttrValus (row) {
      await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(' ')
        })
    },
    handleInputConfirm (row) {
      const inputValue = row.inputValue
      if (inputValue) {
        row.attr_vals.push(inputValue)
        this.saveAttrValus(row)
      }
      row.inputVisible = false
      row.inputValue = ''
    },
    handleRemoveAttr (i, row) {
      row.attr_vals.splice(i, 1)
      this.saveAttrValus(row)
    }
  },
  computed: {
    // 返回的是boolen值
    isBtnDisable () {
      return this.selectedKeys.length !== 3
    },
    cateId () {
      return this.selectedKeys[this.selectedKeys.length - 1]
    },
    titleText () {
      return this.activeName === 'many' ? '动态参数' : '静态参数'
    }
  }
}
</script>
<style lang="less" scoped>
.el-row {
  margin: 15px 0;
}
.el-tag {
  margin: 0 15px;
}
.el-tag + .el-tag {
    margin-left: 10px;
  }
  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }
  .input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }
</style>
